<?php

class Settings extends CI_Model {

	function __construct() {
    	parent::__construct();
    }

    /**
     * Return a full list of settings
     * @return array
     */
    public function get_settings() {
        // Get everything in the settings table
        $query = $this->db->get('settings');
        // Return settings as an array
        $result = $query->result_array();
        // Data to be returned
        $return = array();
        // Make the array
        foreach ($result as $key => $value) {
            $new_key = $value['setting_key'];
            $new_value = $value['setting_value'];
            $return[$new_key] =  $new_value;
        }
        return $return;
    }

    /**
     * Return the value of an individual setting
     * @param string key - The key value for the setting
     * @return string
     */
    public function get_setting($key) {
        $this->db->select('setting_value');
        $this->db->where('setting_key', $key);
        $result = $this->db->get('settings');
        $return = $result->row_array();
        $return = $return['setting_value'];
        return $return;
    }

    /**
     * Update settings/setting
     * @param array settings
     * @return bool
     */
    public function update_settings($settings) {	
        // Get an array of the existing settings
        $current_settings = $this->get_settings();
        $existing = array();
        foreach ($current_settings as $setting => $value) {
            array_push($existing, $setting);
        }
        // Check if the setting has already been set
        foreach ($settings as $key => $value) {
            if ( in_array($key, $existing) ) {
                // It has been set... Update it!
                $this->db->where('setting_key', $key);
                $this->db->set('setting_value', $value);
                $this->db->update('settings'); 
                $this->session->set_flashdata('notices', 'Settings updated successfully.' );
            } else {
                // Setting is new... Insert it!
                $this->db->set('setting_key', $key);
                $this->db->set('setting_value', $value);
                $this->db->insert('settings'); 
                $this->session->set_flashdata('notices', 'Settings updated successfully.' );
            }
        }
    }

}